package com.xw.fileselector;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import com.xw.file_selector.FileSelector;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_xlsx).setOnClickListener(view -> {

            FileSelector.create(this)
                    .choose(new String[]{"xlsx","pdf"})
                    .maxSelect(1)
                    .start(1001);
        });

        findViewById(R.id.btn_other).setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//筛选器
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent,"选择一个文件"),1002);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }

        if (requestCode == 1001 && resultCode == RESULT_OK) {
            List<String> paths = FileSelector.obtainPathsResult(data);
            if (paths != null && paths.size() > 0) {
                for (int i = 0; i < paths.size(); i++) {
                    Log.d("info","==文件地址=" + paths.get(i));
                }
            }
        } else if (requestCode == 1002 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Log.d("info","==文件路径:===" + Uri2Path(uri));

        }
    }

    public String Uri2Path(Uri uri) {
        if (uri == null) {
            return null;
        }

        if(ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return uri.getPath();
        }
        else if(ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            String authority = uri.getAuthority();

            if(authority.startsWith("com.android.externalstorage")) {
                return Environment.getExternalStorageDirectory() + "/" + uri.getPath().split(":")[1];
            }
            else {
                String idStr = "";
                if(authority.equals("media")) {
                    idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1);
                }
                else if(authority.startsWith("com.android.providers")) {
                    idStr = DocumentsContract.getDocumentId(uri).split(":")[1];
                }

                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"),
                        new String[] {MediaStore.Files.FileColumns.DATA},
                        "_id=?",
                        new String[]{idStr}, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    try {
                        int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);

                        return cursor.getString(idx);
                    } catch (Exception e) {
                    } finally {
                        cursor.close();
                    }
                }
            }
        }
        return null;
    }

}